package com.apache.portal.common.util;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.client.InfoReleaseCoreCleint;
import com.apache.passport.entity.Token;
import com.apache.portal.common.oscache.OsCacheManager;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * description:  portal工具类
 *
 * @author Hou Dayu 创建时间：2016-6-15
 */
public class PortalUtil {
    private static PortalUtil instance;

    //    private static transient PubWebSorcketClient websocketClient;
    //
    //    private static Map<String, PubWebSorcketClient> wsClient = new HashMap<String, PubWebSorcketClient>();

    private PortalUtil() {
    }

    public static PortalUtil getInstance() {
        if (null == instance) {
            instance = new PortalUtil();
        }
        return instance;
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        LoginUser loginUser = null;
        boolean isMobile = PortalPubFactory.getInstance().JudgeIsMoblie(request);
        loginUser = PBOSSOTools.getLoginUser(request);//有时，移动端也能获取到
        if (isMobile && loginUser==null) {
            String tokenId = request.getParameter("tokenId");
            loginUser = OsCacheManager.getInstance().getLoginUser(tokenId);
            if (ToolsUtil.isEmpty(loginUser)) {
                if ("wx".equalsIgnoreCase(request.getParameter("userAgent"))) {
                    loginUser = getUserForWx(tokenId);
                } else {
                    loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenId);
                }
                OsCacheManager.getInstance().putLoginUser(tokenId, loginUser);
            }
        }
//        else {
//            loginUser = PBOSSOTools.getLoginUser(request);
//        }
        return loginUser;
    }

    public LoginUser getLoginUser(HttpServletRequest request, String tokenId, String userAgent) {
        LoginUser loginUser = null;
        boolean isMobile = true;
        if (StrUtil.isNull(userAgent)) {
            isMobile = PortalPubFactory.getInstance().JudgeIsMoblie(request);
        }
        String tokenid = StrUtil.doNull(request.getParameter("tokenId"), tokenId);
        if (isMobile && StrUtil.isNotNull(tokenid)) {
            loginUser = OsCacheManager.getInstance().getLoginUser(tokenid);
            if (ToolsUtil.isEmpty(loginUser)) {
                if ("wx".equalsIgnoreCase(request.getParameter("userAgent"))) {
                    loginUser = getUserForWx(tokenid);
                } else {
                    loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenid);
                }
                OsCacheManager.getInstance().putLoginUser(tokenid, loginUser);
            }
        } else {
            loginUser = PBOSSOTools.getLoginUser(request);
        }
        return loginUser;
    }

    public LoginUser getUserForWx(String openId) {
        LoginUser loginUser = null;
        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_interface_pass"));
        map.put("openId", openId);
        Object obj = InfoReleaseCoreCleint.getInstance().selectInfo(map);
        if (obj instanceof Map) {
            Map<String, String> wuser = (Map) obj;
            loginUser = PBOSSOTools.getLoginUserFromUserCenter(wuser.get("userEname"), "token");
        }
        return loginUser;
    }

    public Token getWxToken(String openId) {
        Token token = (Token) OsCacheManager.getInstance().getCustomerUser("token_" + openId);
        if (null == token) {
            LoginUser loginUser = OsCacheManager.getInstance().getLoginUser(openId);
            if (ToolsUtil.isEmpty(loginUser)) {
                loginUser = getUserForWx(openId);
                OsCacheManager.getInstance().putLoginUser(openId, loginUser);
            }

            Map<String, Object> maps = new HashMap<String, Object>();
            String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
            maps.put("userEname", loginUser.getUserEname());
            maps.put("userPass", loginUser.getUserPass());
            maps.put("sysEname", sysEname);
            maps.put("addressIP", "127.0.0.1");
            ResultEntity entity = LoadRpcService.service()
                    .doServiceClient("ssoService", "outSideSocketLoginService", maps,
                            PortalPubFactory.getInstance().getRpcInfo("sso"));
            if (!ToolsUtil.isEmpty(entity.getEntity()) && entity.getEntity() instanceof Token) {
                token = (Token) entity.getEntity();
                OsCacheManager.getInstance().putCustomerUser("token_" + openId, token);
            }
        }
        return token;
    }


    /*public static PubWebSorcketClient getWebsocketCLient(String propKey, String reqUrl) {
        if (null == wsClient.get(reqUrl)) {
            try {
                PubWebSorcketClient websocketClient = new PubWebSorcketClient(
                        new URI(ToolsUtil.getInstance().getValueByKey(propKey) + reqUrl),
                        new Draft_6455()); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts
                websocketClient.connect();
                wsClient.put(reqUrl, websocketClient);
            } catch (Exception e) {
            }
        }
        return wsClient.get(reqUrl);
    }*/

   /* public static PubWebSorcketClient getWebsocketFlowCLient(String flowUrl) {
        if (null == websocketClient) {
            try {
                websocketClient = new PubWebSorcketClient(
                        new URI(ToolsUtil.getInstance().getValueByKey("websocket_url") + flowUrl),
                        new Draft_6455()); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts
                websocketClient.connect();
            } catch (Exception e) {
            }
        }
        return websocketClient;
    }*/

    public String createSeqNo(String seqEname, String noLen) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("seqEname", seqEname);
        params.put("strLen", Validator.getDefaultStr(noLen, "9"));
        InterfaceRegister ss = PortalPubFactory.getInstance().getRpcInfo("seq");
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("seqService", "seqNextValue", params, ss);
        if ("true".equals(entity.getResult()) && !Validator.isEmpty(entity.getEntity()))
            return String.valueOf(entity.getEntity());
        return "";
    }

    /**
     * description:  按籹据库类型转换排序函数
     *
     * @param cloumnName
     */
    public String getOrderNum(String cloumnName) {
        if ("mysql".equalsIgnoreCase(
                ToolsUtil.getInstance().getValueByKey("jdbc.properties", "database_type"))) {
            return " IF(ISNULL(" + cloumnName + "),1,0)";
        } else {
            return "to_number(" + cloumnName + ") asc nulls last";
        }
    }
}
